package com.example.demo.common;

import com.example.demo.component.WebSocketServer;
import com.example.demo.utils.AesEncryptUtils;
import com.example.demo.utils.FilterUtil;
import com.example.demo.wrapper.RequestWrapper;
import com.example.demo.wrapper.ResponseWrapper;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class EncryptFilter implements Filter {

    Logger log = LoggerFactory.getLogger(this.getClass());
    private static final org.slf4j.Logger log1 = org.slf4j.LoggerFactory.getLogger(WebSocketServer.class);
    @Value("${admin.encrypt.excludeUrl}")
    private String ignoreStr;
    private String[] ignoreArr;
    private static final String METHOD_POST = "POST";
    private static final String METHOD_PUT = "PUT";
    private static final String METHOD_DELETE = "DELETE";


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

    private void getFailResponse(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        out = response.getWriter();
//        out.write("{\n" +
//                "    \"status\":"+ Constant.ENCRYPT_FAIL +",\n" +
//                "    \"message\": null,\n" +
//                "    \"data\": []\n" +
//                "}");
        //加密后的错误消息
        out.write("+D+JO8tuwkrNbxnTTLdqStifmQceT+LlYETnIG/JZKrbAn+gIiqIp3VbzBV1y6R8B7aY53VM2xHa7cY3Osbnqw==");
        out.flush();
        out.close();
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        if(ignoreArr==null){
            ignoreArr = ignoreStr.split(",");
        }
        HttpServletRequest HttpRequest=(HttpServletRequest)request;
        HttpServletResponse HttpResponse=(HttpServletResponse)response;
        boolean flag=isIgnore(HttpRequest,ignoreArr);
        if(flag) {
            try {
                chain.doFilter(HttpRequest, HttpResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            try{
                RequestWrapper requestWrapper = null;
                //响应处理  包装响应对象 res 并缓存响应数据
                ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response);
                if (((HttpServletRequest) request).getMethod().equals(METHOD_POST) || ((HttpServletRequest) request).getMethod().equals(METHOD_PUT)){
                    //获取请求报文
                    String requestBody = FilterUtil.getRequestBody(HttpRequest);
                    //对请求报文做解密处理
                    String decryptBASE64="";
                    try {
                        decryptBASE64 = new String(AesEncryptUtils.decrypt(requestBody, "f8db034bda44rtkb"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    requestWrapper = new RequestWrapper(HttpRequest, decryptBASE64);
                    //设置请求头
//                    requestWrapper.addHeader("content-type","application/json");
                    chain.doFilter(requestWrapper, responseWrapper);
                } else
                    chain.doFilter(request, responseWrapper);

//                Map<String, String> objectObjectHashMap = new HashMap<>();
//                objectObjectHashMap.put("content-type","application/json");
//                String headerNames = requestWrapper.getHeader("content-type");
//                String httpServletRequestHeader = HttpRequest.getHeader("content-type");

                //执行业务逻辑 交给下一个过滤器或servlet处理
                byte[] resData = responseWrapper.getResponseData();
                //设置响应内容格式，防止解析响应内容时出错
//                 responseWrapper.setContentType(headerNames);
//                 responseWrapper.setHeader(httpServletRequestHeader);
                //加密响应报文并响应
                byte[] encryptBASE64 = AesEncryptUtils.encrypt(new String(resData,"utf-8"),"f8db034bda44rtkb");
                String encryptStr=AesEncryptUtils.parseByte2HexStr(encryptBASE64);
//                log1.info("加密后：", encryptStr);
                PrintWriter out = response.getWriter();
                out.print(encryptStr);
                out.flush();
                out.close();

            }catch(Exception e){
                try {
                    getFailResponse((HttpServletResponse)response);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                e.printStackTrace();
            }
        }
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * 哪些路径不处理
     */
    public boolean isIgnore(HttpServletRequest request, String[] strArr) {
        String path=request.getRequestURI();
        for(String ignore:strArr) {
            if(path.contains(ignore)) {
                return true;
            }
        }
        return false;
    }
}
